package cn.iocoder.yudao.module.infra.controller.admin.ueditor;

import cn.hutool.core.io.IoUtil;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import com.google.gson.Gson;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @author pg
 * @project zysx
 * @description 编辑器
 * @date 2024/10/30 10:10:25
 */
@Tag(name = "编辑器")
@RestController
@RequestMapping("/infra/ueditor")
@Validated
@Slf4j
public class UeditorController {

    @Resource
    private FileService fileService;

    @RequestMapping("/config")
    @Operation(summary = "读取配置") // 由 pay-module 支付服务，进行回调，可见 PayNotifyJob
    @PermitAll
    @OperateLog(enable = false) // 禁用操作日志，因为没有操作人
    public String config(HttpServletRequest request, HttpServletResponse response, String action, String callback, MultipartFile upfile) throws IOException {
        log.info("开始读取配置");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/javascript");

        if ("config".equals(action)) {
            PrintWriter fileWriter = response.getWriter();

            String result = parseJsonWithGson();
            if (callback != null && !callback.isEmpty()) {
                fileWriter.write(callback + "(" + result.replace(";", "") + ")");
            } else {
                fileWriter.write(result);
            }
            fileWriter.flush();
            fileWriter.close();
        } else if ("uploadimage".equals(action)) {
            log.info("上传图片");
            UEditorFile uEditorFile = new UEditorFile();
            // 处理上传图片逻辑并返回结果
            String fileName = upfile.getOriginalFilename();
            String returnPath = "ueditor/image/" + new Date().getTime() + "/" + fileName;
            fileService.createFile(upfile.getOriginalFilename(), returnPath, IoUtil.readBytes(upfile.getInputStream()));
            uEditorFile.setUrl("/" + returnPath);
            uEditorFile.setState("SUCCESS");
            uEditorFile.setTitle(fileName);
            uEditorFile.setOriginal(fileName);
            // 如果有回调，则将结果包裹在 callback() 中
            if (callback != null && !callback.isEmpty()) {
                return callback + "(" + new Gson().toJson(uEditorFile) + ")";
            } else {
                return new Gson().toJson(uEditorFile);
            }
        }
        return null;
    }

    public String parseJsonWithGson() {
        ClassPathResource resource = new ClassPathResource("file/admin-api/infra/ueditor/config.json");
        try (InputStream inputStream = resource.getInputStream();
             JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream))) {

            jsonReader.setLenient(true); // 启用宽松模式，允许注释
            JsonElement jsonElement = JsonParser.parseReader(jsonReader);

            // 使用 Gson 转换为 JSON 字符串
            return new Gson().toJson(jsonElement);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
